<template>
  <div id="app-container">
    <!-- 显示流步骤 -->
    <el-steps :active="1" align-center process-status="wait" style="margin-bottom: 40px">
      <el-step title="填写课程基本信息"></el-step>
      <el-step title="创建课程大纲"></el-step>
      <el-step title="发布课程"></el-step>
    </el-steps>

    <div id="app-canvas">
    <el-form style="width: 400px;overflow: hidden" label-position="right">

      <el-form-item label="课程标题">

        <el-input v-model="courseInfo.title" style="width: 19rem" placeholder="示例：Java基础入门: 通俗易懂，保姆式教程"/>
      </el-form-item>

      <el-form-item label="总课时">
        <span v-html="'\u00a0\u00a0\u00a0\u00a0'"></span>
        <el-input-number style="width: 19rem" :min="0" v-model="courseInfo.lessonNum" placeholder="请填写课程的总课时数"/>
      </el-form-item>

      <el-form-item label="课程简介">
        <!--        <el-input type="textarea" style="width: 19rem" placeholder="请填写课程简介" v-model="courseInfo.description"-->
        <!--                  maxlength="100" show-word-limit>-->
        <!--        </el-input>-->

        <editor id="tinymce" v-model="courseInfo.description" :init="init"></editor>

      </el-form-item>

      <el-form-item label="课程价格">
        <el-input-number :min="0" v-model="courseInfo.price" style="width: 17rem" placeholder="免费课程请设置为0元"/>
        <span v-html="'\u00a0\u00a0'"> </span> 元
      </el-form-item>

      <!--课程讲师-->
      <el-form-item label="课程讲师">
        <el-select v-model="courseInfo.teacherId" placeholder="请选择" style="width: 19rem">
          <el-option v-for="teacher in teacherList" :key="teacher.id" :label="teacher.name" :value="teacher.id"
                     style="width: 17rem"/>
        </el-select>
      </el-form-item>

      <!--课程分类-->
      <el-form-item label="课程分类">
        <el-select v-model="courseInfo.subjectParentId" placeholder="请选择" style="width: 9rem"
                   @change="subjectLevelOnChanged">
          <el-option v-for="subject in subjectOneList" :key="subject.id" :label="subject.title" :value="subject.id"
                     style="width: 9rem"/>
        </el-select>
        <!-- 二级分类 -->
        <el-select v-model="courseInfo.subjectId" placeholder="选择二级分类" style="width: 10rem">
          <el-option v-for="subject in subjectTwoList" :key="subject.id"
                     :label="subject.title" :value="subject.id" style="width: 10rem"/>
        </el-select>

      </el-form-item>

      <!--课程封面-->
      <el-form-item label="课程封面">

        <el-upload
          :shaw-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
          :action="BASE_API+'/oss/file/upload'"
          class="avatar-uploader">
          <img style="height: 100px" :src="courseInfo.cover">
        </el-upload>

      </el-form-item>


      <el-form-item>
        <el-button :disabled="!this.$route.query.isList" style="margin: 0 4rem;" @click="back" type="primary">回到上一步</el-button>
        <el-button @click="next()" type="primary">保存并下一步
        </el-button>
      </el-form-item>


    </el-form>
    </div>
  </div>
</template>

<script>
  import course from '@/api/edu/course'
  import teacher from '@/api/edu/teacher'
  import subject from '@/api/edu/subject'
  import tinymce from 'tinymce'
  import Editor from '@tinymce/tinymce-vue'
  import 'tinymce/themes/silver/theme'
  //如果报错找不到  import 'tinymce/themes/modern/theme',可以替换成 import 'tinymce/themes/silver/theme'
  //不过一般都会报错,说找不到的....
  // 添加更多功能：
  import 'tinymce/plugins/image'
  import 'tinymce/plugins/link'
  import 'tinymce/plugins/code'
  import 'tinymce/plugins/table'
  import 'tinymce/plugins/lists'
  import 'tinymce/plugins/wordcount'

  export default {
    name: 'info',
    components: { Editor },
    data() {
      return {
        courseInfo: {
          title: '',
          subjectId: '', //二级分类id
          subjectParentId: '',// 一级分类id
          teacherId: '',
          lessonNum: 0,
          description: ' ',
          cover: 'http://oss.hewentao.tk/2022%2F08%2Fshang_chuan_tu_pian.png', // 封面地址
          price: 0
        },
        teacherList: [],
        subjectOneList: [], // 一级分类集合
        subjectTwoList: [], // 二级分类集合
        BASE_API: process.env.VUE_APP_BASE_API,
        init: {
          selector: '#tinymce', //tinymce的id
          language_url: '/static/tinymce/langs/zh_CN.js',
          content_css: '/static/tinymce/skins/content/document/content.css',
          language: 'zh_CN',
          skin_url: '/static/tinymce/skins/ui/oxide', //编辑器需要一个skin才能正常工作，所以要设置一个skin_url指向之前复制出来的skin文件
          plugins: 'image link code table lists wordcount', // 添加引入的插件
          paste_data_images: true, // 允许粘贴图像
          font_formats: '微软雅黑=Microsoft YaHei,Helvetica Neue;PingFang SC;sans-serif;苹果苹方=PingFang SC,Microsoft YaHei,sans-serif;宋体=simsun;serifsans-serif;Terminal=terminal;monaco;Times New Roman=times new roman;times', //字体
          toolbar: 'fontselect fontsizeselect link lineheight forecolor backcolor bold italic underline strikethrough | alignleft aligncenter alignright alignjustify | image quicklink h2 h3 blockquote table numlist bullist preview fullscreen', // 自定义工具栏
          images_upload_handler: function(blobInfo, success, failure) { // 图片上传配置
            let formdata = new FormData()
            formdata.append('file', blobInfo.blob())

            //是上传图片的请求接口
            course.addImage(formdata)
              .then(res => {
                console.log(res)

                // 获取返回的 url
                success(res.data.url)
              })
              .catch(res => {

                failure('error')

              })
          }
        },
        courseId: 0
      }
    },
    methods: {

      back() {
        if (this.$route.query.isList) {
          this.$router.push('/course/list')
        }else {
          this.$router.push('/course/save/info/' + this.chapter.courseId)
        }
      },

      next() {
          if (this.$route.params && this.$route.params.id) {  // 判断是否为修改
            course.updateCourseInfo(this.courseInfo).then(res => {
              this.$message.success(res.message)
              // 跳转第二步
              if (this.$route.query.isList) {
                this.$router.push('/course/list')
              }else {
                this.$router.push('/course/save/chapter/' + this.courseId)
              }
            })

          } else {  // 判断为添加
            course.addCourseInfo(this.courseInfo)
              .then(res => {
                this.$message.success(res.message)
                // 保存返回的 id
                this.courseId = res.data.courseId
                // 跳转第二步
                this.$router.push('/course/save/chapter/' + this.courseId)
              })
          }

      }
      ,
      // 点击一级菜单栏选项时，获取对应的二级菜单值
      subjectLevelOnChanged(value) {
        // value 就是选择的值
        for (let i = 0; i < this.subjectOneList.length; i++) {
          if (this.subjectOneList[i].id === value) {
            this.subjectTwoList = this.subjectOneList[i].children
            this.courseInfo.subjectId = ''
          }
        }
      }
      ,
      // 头像上传成功回调函数
      handleAvatarSuccess(res, file) {
        this.courseInfo.cover = res.data.url
      }
      ,
      // 头像上传之前回调函数
      beforeAvatarUpload(file) {

        const isJPG = file.type === 'image/jpeg'
        const isLt2M = file.size / 1024 / 1024 < 2
        if (!isJPG) {
          this.$message.error('上传头像图片只能是JPG格式!')
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过2MB!')
          return isJPG && isLt2M

        }
      }

    },
    created() {
      // 设置步骤图为当前步骤
      this.$store.dispatch('app/saveActive', 1)

      // 查询所有讲师
      teacher.getAllTeacher().then(res => {
        this.teacherList = res.data.items
      })

      // 判断是否是回退
      if (this.$route.params && this.$route.params.id) {
        // 保存课程 id
        this.courseId = this.$route.params.id

        // 如果是回退的，先进行加载数据，
        course.getCourseInfo(this.courseId).then(res => {
          let datares = res.data

          // 加载成功之后，再获取到对应的课程分类
          subject.getSubjectList().then(res => {
            // 将一级课程分类进行赋值
            this.subjectOneList = res.data.children
            // 将二级课程分类进行赋值
            this.subjectLevelOnChanged(datares.courseInfoVo.subjectParentId)
            // 最后赋值数据，这样可以防止刷新出现显示 id 问题
            this.courseInfo = datares.courseInfoVo

          })
        })
      } else {
        // 不是回退的话，直接查询所有课程分类
        subject.getSubjectList().then(res => {
          this.subjectOneList = res.data.children
        })
      }

      // 富文本编辑器配置
      tinymce.init({})

    }
  }
</script>

<style scoped>

  /* 设置组件位置 */
  #app-canvas {

    width: 400px;
    overflow: hidden;
    margin: 1px auto;
    position: static;
  }


</style>
